package com.ztr.crud_demo.utils;

import org.springframework.stereotype.Component;

/*
*  Twitter的分布式自增ID雪花算法
* */
@Component
public class SnowFlake {

    /** 初始时间，目前为2023年1月1日0时0分0秒 */
    private final long twepoch = 1672502400000l;
    /** 服务id位数 */
    private int workerIdBits = 5;
    /** 机器id位数 */
    private int datacenterIdBits = 5;
    /** 最大服务位数 */
    private int maxWorkerId = -1 ^ (-1 << workerIdBits);
    /** 最大机器id位数 */
    private int maxDatacenterId = -1 ^ (-1 << datacenterIdBits);
    /** 序号位数 */
    private int sequenceBits = 12;
    /** 服务id需要左移位数 */
    private int workerIdShift = sequenceBits;
    /** 机器id需要左移位数 */
    private int datacenterIdShift = sequenceBits + workerIdBits;
    /** 时间戳需要左移的位数 */
    private int timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private int sequenceMask = -1 ^ (-1 << sequenceBits);
    /** 服务id */
    private int workerId;
    /** 机器id */
    private int datacenterId;
    private long lastTimestamp = -1;
    /** 每秒生成id序号 */
    private int sequence = 0;

    public SnowFlake(){

    }
    /**
     * 获取自定义雪花算法类
     * @param workerIdBits 服务id比特位数
     * @param datacenterIdBits 机器id比特位数
     * @param sequenceBits 序号比特位数
     * @param workerId 服务id
     * @param datacenterId 机器id
     */
    public SnowFlake(int workerIdBits, int datacenterIdBits, int sequenceBits, int workerId, int datacenterId) {
        if(workerIdBits + datacenterIdBits + sequenceBits > 22){
            throw new IllegalArgumentException(String.format("workerIdBits, datacenterIdBits, sequenceBits 之和不能超过22"));
        }
        int maxWorkerId = -1 ^ (-1 << workerIdBits);
        int maxDatacenterId = -1 ^ (-1 << datacenterIdBits);

        if (workerId < 0 || workerId > maxWorkerId) {
            throw new IllegalArgumentException(String.format("workerId 必须在 0 和 %d 之间", maxWorkerId));
        }
        if (datacenterId < 0 || datacenterId > maxDatacenterId) {
            throw new IllegalArgumentException(String.format("datacenterId 必须在 0 和 %d 之间", maxDatacenterId));
        }

        this.workerIdBits = workerIdBits;
        this.datacenterIdBits = datacenterIdBits;
        this.sequenceBits = sequenceBits;
        this.maxWorkerId = maxWorkerId;
        this.maxDatacenterId = maxDatacenterId;
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.workerIdShift = sequenceBits;
        this.datacenterIdShift = sequenceBits + workerIdBits;
        this.timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
        this.sequenceMask = -1 ^ (-1 << sequenceBits);
    }

    /**
     * 获取默认雪花算法类
     * @param workerId 服务id，最大值为31
     * @param datacenterId 机器id，最大值为31
     */
    public SnowFlake(int workerId, int datacenterId) {
        if (workerId < 0 || workerId > maxWorkerId) {
            throw new IllegalArgumentException(String.format("workerId 必须在 0 和 %d 之间", maxWorkerId));
        }
        if (datacenterId < 0 || datacenterId > maxDatacenterId) {
            throw new IllegalArgumentException(String.format("datacenterId 必须在 0 和 %d 之间", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("时间回调了，无法在 %d 毫秒内生成id", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }
}
